﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BLL;
using Model;
using Util;

namespace UI
{
    public partial class OperateKnifeDisableForm : Form, InterfaceSelect
    {
        OperateInOutBLL bll = new OperateInOutBLL();
        PlaceAreaBLL sbll = new PlaceAreaBLL();
        RuningDoListBLL dbll = new RuningDoListBLL();
        MaterielBLL mbll = new MaterielBLL();
        MachineBLL mBll = new MachineBLL();
        PlaceBLL pbll = new PlaceBLL();
        MaterielTypeBLL tbll = new MaterielTypeBLL();
        DataTable dt;
        DataTable dtBak = new DataTable();
        InOutType inOutType = InOutType.KNIFE_IN_USE;
        public T_JB_Materiel materielNow;
        int max1, max2, max3, max4 = 0;
        bool isScan = false;

        public OperateKnifeDisableForm()
        {
            InitializeComponent();
        }

        private void OperateKnifeDisableForm_Load(object sender, EventArgs e)
        {
            initData();

            #region 初始化 物料类别
            DataTable dt = tbll.GetList(null, null, null, 1);
            DataView dataView = dt.DefaultView;
            dataView.Sort = "C_ID asc";
            cmbType.DataSource = dataView.ToTable();
            cmbType.DisplayMember = "C_NAME";
            cmbType.ValueMember = "C_ID";
            cmbType.SelectedIndex = -1;
            #endregion

            #region 初始化 货区
            DataTable dtt = sbll.GetList(null);
            DataView dataViewt = dtt.DefaultView;
            dataViewt.Sort = "C_ID asc";
            cmbArea.DataSource = dataViewt.ToTable();
            cmbArea.DisplayMember = "C_NAME";
            cmbArea.ValueMember = "C_ID";
            cmbArea.SelectedIndex = -1;
            #endregion

            #region 初始化 机床
            DataTable dtm = mBll.GetList();
            cmbMachine.DataSource = dtm.DefaultView;
            cmbMachine.DisplayMember = "C_ID";
            cmbMachine.ValueMember = "C_ID";
            cmbMachine.SelectedIndex = -1;
            #endregion

            txtId.Focus();
        }

        //确认
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (checkInput())
            {
                addRowMult(dtBak);
                initSub();

                dtBak.Clear();
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        //报废
        private void btnShouGong_Click(object sender, EventArgs e)
        {
            if (dt.Rows.Count <= 0)
            {
                MessageBox.Show("没有要入库的记录!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                try
                {
                    if (bll.HasDoList())
                    {
                        MessageBox.Show("存在未完成的联机任务，不能进行出入库操作!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    if (bll.DisableKnife(dt))
                    {
                        MessageBox.Show("刀具报废成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Log.saveLog("刀具报废成功！");
                        initSub();
                        dt.Rows.Clear();
                    }
                    else
                    {
                        MessageBox.Show("入库失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("与数据库连接失败，请查看网络连接是否正常。如不能解决请与网络管理员联系！", "严重错误：", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        //选择物料
        private void button3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cmbMachine.Text.Trim()))
            {
                MessageBox.Show("请先选择机床！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            SelectKnifeUse();
        }

        /// <summary>
        /// 选择刀具
        /// </summary>
        /// <param name="mo"></param>
        private void SelectKnifeUse()
        {
            dtBak = dt.Clone();

            SelectKnifeUseForm select = new SelectKnifeUseForm(cmbMachine.Text.Trim(), dt, dtBak);
            select.ShowDialog();

            if (dtBak.Rows.Count > 0)
            {
                ModelToUI(mbll.getMaterielById(dtBak.Rows[0][0].ToString()));

                //txtInPlace.Text = dtBak.Rows[0][4].ToString();

                max1 = Convert.ToInt32(dtBak.Rows[0][3].ToString());
                max2 = Convert.ToInt32(dtBak.Rows[0][9].ToString());
                max3 = Convert.ToInt32(dtBak.Rows[0][10].ToString());
                max4 = Convert.ToInt32(dtBak.Rows[0][11].ToString());

                cbCount1.Checked = max1 == 1;
                cbCount2.Checked = max2 == 1;
                cbCount3.Checked = max3 == 1;
                cbCount4.Checked = max4 == 1;
            }
        }

        private void addRowMult(DataTable dtBak)
        {
            int c1 = cbCount1.Checked ? 1 : 0;
            int c2 = cbCount2.Checked ? 1 : 0;
            int c3 = cbCount3.Checked ? 1 : 0;
            int c4 = cbCount4.Checked ? 1 : 0;

            if (isScan)
            {
                for (int j = 0; j < dtBak.Rows.Count; j++)
                {
                    bool b1, b2, b3, b4;
                    bool bo1, bo2, bo3, bo4;

                    bo1 = cbCount1.Checked;
                    b1 = (int)Convert.ToSingle(dtBak.Rows[j][3].ToString()) == 1;

                    bo2 = cbCount2.Checked;
                    b2 = (int)Convert.ToSingle(dtBak.Rows[j][9].ToString()) == 1;

                    bo3 = cbCount3.Checked;
                    b3 = (int)Convert.ToSingle(dtBak.Rows[j][10].ToString()) == 1;

                    bo4 = cbCount4.Checked;
                    b4 = (int)Convert.ToSingle(dtBak.Rows[j][11].ToString()) == 1;

                    if ((bo1 && b1) || (bo2 && b2) || (bo3 && b3) || (bo4 && b4))
                    {
                        DataRow dr = dt.NewRow();
                        dr[0] = dtBak.Rows[j][0];
                        dr[1] = dtBak.Rows[j][1];
                        dr[2] = dtBak.Rows[j][2];
                        dr[3] = bo1 && b1 ? 1 : 0;
                        dr[4] = bo2 && b2 ? 1 : 0;
                        dr[5] = bo3 && b3 ? 1 : 0;
                        dr[6] = bo4 && b4 ? 1 : 0;
                        dr[7] = dtBak.Rows[j][4];
                        dr[9] = dtBak.Rows[j][6];
                        dr[10] = dtBak.Rows[j][7];
                        dr[11] = dtBak.Rows[j][8];
                        dr[13] = dtBak.Rows[j][12];

                        if (b1 ? bo1 == b1 : true && b2 ? bo2 == b2 : true && b3 ? bo3 == b3 : true && b4 ? bo4 == b4 : true)
                        {
                            dr[12] = 2;
                        }
                        else
                        {
                            dr[12] = 1;
                        }

                        dt.Rows.InsertAt(dr, 0);
                    }
                }

                isScan = false;
            }
            else
            {
                for (int j = 0; j < dtBak.Rows.Count; j++)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = dtBak.Rows[j][0];
                    dr[1] = dtBak.Rows[j][1];
                    dr[2] = dtBak.Rows[j][2];
                    dr[3] = c1;
                    dr[4] = c2;
                    dr[5] = c3;
                    dr[6] = c4;
                    dr[7] = dtBak.Rows[j][4];
                    dr[9] = dtBak.Rows[j][6];
                    dr[10] = dtBak.Rows[j][7];
                    dr[11] = dtBak.Rows[j][8];
                    dr[13] = dtBak.Rows[j][12];

                    if (c1 == max1 && c2 == max2 && c3 == max3 && c4 == max4)
                    {
                        dr[12] = 2;
                    }
                    else
                    {
                        dr[12] = 1;
                    }

                    dt.Rows.InsertAt(dr, 0);
                }
            }
        }

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void initData()
        {
            dt = new DataTable();

            for (int i = 0; i < 14; i++)
            {
                DataColumn column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = i.ToString();

                dt.Columns.Add(column);
            }

            this.dgv_Data.DataSource = dt;
            getName();
        }

        /// <summary>
        /// 设置dg列名
        /// </summary>
        private void getName()
        {
            dgv_Data.Columns[0].HeaderText = "物料编码";
            dgv_Data.Columns[1].HeaderText = "物料名称";
            dgv_Data.Columns[2].HeaderText = "规格型号";
            dgv_Data.Columns[3].HeaderText = "上模数量";
            dgv_Data.Columns[4].HeaderText = "0.25数量";
            dgv_Data.Columns[5].HeaderText = "0.5数量";
            dgv_Data.Columns[6].HeaderText = "退料板数量";
            dgv_Data.Columns[7].HeaderText = "货位";
            dgv_Data.Columns[8].HeaderText = "入库日期";
            dgv_Data.Columns[8].Visible = false;
            dgv_Data.Columns[9].HeaderText = "操作员";
            dgv_Data.Columns[9].Visible = false;
            dgv_Data.Columns[10].HeaderText = "机床";
            dgv_Data.Columns[11].HeaderText = "编号";
            dgv_Data.Columns[11].Visible = false;
            dgv_Data.Columns[12].HeaderText = "标志";
            dgv_Data.Columns[12].Visible = false;
            dgv_Data.Columns[13].HeaderText = "首次入库日期";
            dgv_Data.Columns[13].Visible = false;
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        /// <returns></returns>
        private bool checkInput()
        {
            bool flag = true;

            if (cbCount1.Checked && max1 == 0)
            {
                flag = false;
                MessageBox.Show("上模数量大于可用数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            if (cbCount2.Checked && max2 == 0)
            {
                flag = false;
                MessageBox.Show("0.25数量大于可用数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            if (cbCount3.Checked && max3 == 0)
            {
                flag = false;
                MessageBox.Show("0.5数量大于可用数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            if (cbCount4.Checked && max4 == 0)
            {
                flag = false;
                MessageBox.Show("退料板数量大于可用数量！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            return flag;
        }

        private void initSub()
        {
            //txtInPlace.Text = string.Empty;

            txtMaterielName.Text = string.Empty;
            txtId.Text = string.Empty;
            txtStand.Text = string.Empty;

            txtMT.Text = string.Empty;
            txtLT.Text = string.Empty;
            txtWT.Text = string.Empty;
            txtMeno.Text = string.Empty;
            txtId.Text = string.Empty;
            this.txtDim1.Text = string.Empty;
            this.txtDim2.Text = string.Empty;
            this.txtDim3.Text = string.Empty;
            this.txtAngle.Text = string.Empty;
            this.txtRL.Text = string.Empty;
            cbBoard.Checked = false;

            cbCount1.Checked = false;
            cbCount2.Checked = false;
            cbCount3.Checked = false;
            cbCount4.Checked = false;

            max1 = 0;
            max2 = 0;
            max3 = 0;
            max4 = 0;

            txtId.Focus();
        }

        private void dgv_Data_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                string materiel = dt.Rows[e.RowIndex][0].ToString();
                int i = 0;
                for (; i < dt.Rows.Count; i++)
                {
                    if (materiel.Equals(dt.Rows[i][0]))
                    {
                        break;
                    }
                }
                if (i < dt.Rows.Count)
                {
                    dt.Rows.Remove(dt.Rows[i]);
                }
            }
        }

        /// <summary>
        /// 显示model
        /// </summary>
        /// <param name="materiel"></param>
        void ModelToUI(T_JB_Materiel materiel)
        {
            this.txtId.Text = materiel.C_id;
            this.txtMaterielName.Text = materiel.C_name;
            this.cmbType.SelectedValue = materiel.C_type;
            this.txtStand.Text = materiel.C_standerd;
            this.txtMT.Text = materiel.I_thick.ToString();
            this.txtLT.Text = materiel.I_length.ToString();
            this.txtWT.Text = materiel.I_width.ToString();
            this.cmbArea.SelectedValue = materiel.C_area;

            this.txtMeno.Text = materiel.C_memo;
            this.txtDim1.Text = materiel.Dec_dimension1.ToString();
            this.txtDim2.Text = materiel.Dec_dimension2.ToString();
            this.txtDim3.Text = materiel.Dec_dimension3.ToString();
            this.txtAngle.Text = materiel.Dec_angle.ToString();
            this.txtRL.Text = materiel.C_regrinding_length;
            cbBoard.Checked = materiel.I_buy == 1;
        }




        #region InterfaceSelect 成员

        public void setMateriel(string name, string id)
        {
            throw new NotImplementedException();
        }
        public void setMateriel(string name, string id, string standard)
        {
            try
            {
                materielNow = mbll.getMaterielById(id);
                ModelToUI(materielNow);
            }
            catch (Exception)
            {
                MessageBox.Show("与数据库连接失败，请查看网络连接是否正常。如不能解决请与网络管理员联系！", "严重错误：", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public void setMaterielAndPlace(string mname, string mid, string standard, string pid, string tray, int count, string typeName)
        {
            throw new NotImplementedException();
        }
        public void setMateriel(string name, string id, int thick, int single, string standard, int length, int width)
        {
            throw new NotImplementedException();
        }

        public void setPlace(string name, string id, int length, int width)
        {
        }

        public void setMaterielAndPlace(string mname, string mid, int thick, int single, string standard, int length, int width, string pname, string pid, int plength, int pwidth, int count)
        {
            throw new NotImplementedException();
        }

        #endregion

        private void txtId_KeyPress(object sender, KeyPressEventArgs e)
        {
            //扫码
            if (e.KeyChar == 13)
            {
                max1 = 0;
                max2 = 0;
                max3 = 0;
                max4 = 0;

                if (string.IsNullOrEmpty(cmbMachine.Text.Trim()))
                {
                    MessageBox.Show("请先选择机床！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                string id = txtId.Text.Trim();
                T_JB_Materiel mo = mbll.getMaterielById(id);

                if (mo != null)
                {
                    bool flag = true;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string m = Convert.ToString(dt.Rows[i][0]);
                        string c = Convert.ToString(dt.Rows[i][10]);
                        if (txtId.Text.Equals(m) && cmbMachine.Text.Trim().Equals(c))
                        {
                            flag = false;
                            break;
                        }
                    }

                    if (flag)
                    {
                        DataTable st = bll.getKDList(Global.minValue, Global.minValue, null, cmbMachine.Text.Trim(), InOutType.KNIFE_OUT_USE, id, null);

                        if (st.Rows.Count > 0)
                        {
                            ModelToUI(mo);

                            dtBak = dt.Clone();

                            string place = string.Empty;

                            for (int i = 0; i < st.Rows.Count; i++)
                            {
                                place += st.Rows[i][4].ToString() + ",";

                                max1 += (int)Convert.ToSingle(st.Rows[i][8].ToString());
                                max2 += (int)Convert.ToSingle(st.Rows[i][9].ToString());
                                max3 += (int)Convert.ToSingle(st.Rows[i][10].ToString());
                                max4 += (int)Convert.ToSingle(st.Rows[i][11].ToString());

                                DataRow dr = dtBak.NewRow();
                                dr[0] = st.Rows[i][0].ToString();
                                dr[1] = st.Rows[i][1].ToString();
                                dr[2] = st.Rows[i][3].ToString();
                                dr[4] = st.Rows[i][4].ToString();
                                dr[6] = Global.longid;
                                dr[7] = st.Rows[i][5].ToString();
                                dr[8] = st.Rows[i][7].ToString();
                                dr[3] = (int)Convert.ToSingle(st.Rows[i][8].ToString());
                                dr[9] = (int)Convert.ToSingle(st.Rows[i][9].ToString());
                                dr[10] = (int)Convert.ToSingle(st.Rows[i][10].ToString());
                                dr[11] = (int)Convert.ToSingle(st.Rows[i][11].ToString());
                                dr[12] = st.Rows[i][13].ToString();

                                dtBak.Rows.Add(dr);
                            }


                            //txtInPlace.Text = place.Substring(0, place.Length - 1);

                            cbCount1.Checked = max1 == 1;
                            cbCount2.Checked = max2 == 1;
                            cbCount3.Checked = max3 == 1;
                            cbCount4.Checked = max4 == 1;

                            isScan = true;
                        }
                        else
                        {
                            MessageBox.Show(string.Format("机床：{0}上没有刀具：{1}", cmbMachine.Text.Trim(), id), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                    else
                    {
                        MessageBox.Show(string.Format("刀具：{0}重复扫描！", id), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    MessageBox.Show("无法解析！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
    }
}
